import { getRoutersApi } from '@/api/menu-api';
import Layout from '@/layout/index.vue';



const permission = {
  state() {
    return {
      dynamicRoutesLoaded: false,
      menuTree: [], // 菜单树
      permissions: [], // 权限
      menuList: [] // 扁平菜单
    };
  },
  getters: {
    menuTree: (state) => state.menuTree,
    permissions: (state) => state.permissions,
    flatMenuList: (state) => state.menuList

  },
  mutations: {
    SET_MENU_TREE: (state, payload) => {
      state.menuTree = payload;
      localStorage.setItem('menuTree', JSON.stringify(payload));
    },
    SET_MENU_LIST: (state, payload) => {
      state.menuList = payload;
    },
    SET_PERMISSIONS: (state, payload) => {
      state.permissions = payload;
    },
    SET_DYNAMIC_ROUTES_LOADED(state, payload) {
      state.dynamicRoutesLoaded = payload;
      localStorage.setItem('dynamicRoutesLoaded', payload);
    }
  },
  actions: {
    // api 返回登录用户拥有的动态菜单 ， 这里需要生产动态的菜单导航树和动态访问路由
    async generateRoutes({ dispatch, commit }) {
      try {
        let {
          data: { flatMenuList, permissions, routers }
        } = await getRoutersApi();

        // 存储权限
        commit('SET_PERMISSIONS', permissions);
        // 存储菜单
        commit('SET_MENU_LIST', flatMenuList);

        const asyncRouter = transformRoutes(routers);
        // 存储菜单树
        commit('SET_MENU_TREE', asyncRouter);

        commit('SET_DYNAMIC_ROUTES_LOADED', true);

        // asyncRouter.push({ path: '*', redirect: '/404'});
        // 返回动态路由
        return asyncRouter;
      } catch (error) {
        // 处理错误
        console.error('获取权限菜单列表时出错:', error);

        // 类似于你在原始代码中使用 reject 的方式
        // 如果你想在外部处理这个错误，可以抛出或返回这个错误
        Promise.reject(error);
      }
    },

    // 设置权限
    getPermissions({ commit }, payload) {
      // 用于将树形结构的数据扁平化成一个数组
      const flattenTree = (tree) => {
        return tree.reduce((acc, node) => {
          acc.push(node);
          if (node.children.length) {
            acc.push(...flattenTree(node.children));
          }

          return acc;
        }, []);
      };

      let list = flattenTree(payload);
      let permissions = list.map((item) => item.mark);
      commit('SET_PERMISSIONS', permissions);
    },

    // 设置菜单
    getMenuList({ commit }, payload) {
      commit('SET_MENU_LIST', payload);
    },
    clearPermission({ commit }) {
      commit('SET_MENU_LIST', []);
      commit('SET_PERMISSIONS', []);
    }
  }
};

// 处理路由树的方法
export const transformRoutes = (routers) => {
  return routers.map((route) => {
    if (route.menu_type === 0 || !route.component || route.component === 'layout') {
      route.component = Layout;
      if (route?.children?.length > 0) {
        route.children = transformRoutes(route.children);
      }
    } else if (route.menu_type === 1) {
      if (route?.children?.length > 0) {
        route.children = transformRoutes(route.children);
      } else {
        route.component = loadPage(route.component);
      }
    }

    return {
      id: route.id,
      name: route.name,
      meta: route.meta,
      icon: route.icon,
      parent_id: route.parent_id,
      path: route.path,
      component: route.component,
      children: route.children
    };
  });
};



/**
 * 将拿到的组件数组，转换为组件对象
 * @param {Array} arr 获取到组件信息数组
 */
export const filterAsyncRouter = (arr) => {
  let routers = JSON.parse(JSON.stringify(arr));
  // 获取显示的菜单
  const displayRouters = routers.filter((v) => v.display == 1);
  displayRouters.forEach((item) => {
    item.name = item.name || item.componentName;
    item.path = item.routePath || '/';
    item.component = item.componentPath || 'Layout';
    if (item.type == 0) {
      item.redirect = item.type == 0 ? item?.redirect ?? null : null;
    }
    item.meta = {
      title: item.name,
      icon: item.icon
    };
    if (item.component) {
      // Layout组件特殊处理
      if (item.component === 'Layout') {
        item.component = Layout;
      } else if (item.component === 'empty') {
        item.component = EmptyLayout;
      } else {
        const component = item.component;
        item.component = loadPage(component);
      }
    }
    if (item.children && item.children.length) {
      item.children = filterAsyncRouter(item.children.filter((v) => v.type != 2));
    }
  });

  return displayRouters;
};

/**
 * 加载组件
 * @param {String} path 组件路径
 */
export const loadPage = (path) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views/${path}.vue`], resolve);
  } else {
    return () => import(`@/views/${path}.vue`);
  }
};

export default { namespaced: true, ...permission };
